<?php
/**
 * Description: 新品速递-定时抽奖-创建抽奖任务
 * Created by PhpStorm.
 * User: 玉坤
 * Date: 2021/6/15
 * Time: 14:04
 */

use Biz\model\NewProduct\NewProductWikiModel;
use Biz\model\NewProduct\NewProductLotteryLogModel;
use Biz\model\NewProduct\NewProductWinnerListModel;

ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
ini_set('memory_limit', '1024M');

require_once '/data/wwwroot/g_vendor/autoload.php';


$start = microtime(true);
$page = 1;
$pageSize = 50;
$lists = [];
$all_num = 0;


//获取半年新品速递中奖uid
$new_where = [
    'addtime[>]' => date('Y-m-d H:i:s', strtotime('-6 months')),
    'winner_status[!]' => NewProductWinnerListModel::DELETE
];
$new_uids = NewProductWinnerListModel::select('uid', $new_where);
//员工账号UID
$staffUids = \Biz\tools\helper\Common::getStaffUids();
$uids = array_merge($new_uids, $staffUids) ?: [];


do {
    $limit = [($page - 1) * $pageSize, $pageSize];
    $where = [
        "LIMIT" => $limit,
        'status' => NewProductWikiModel::STATUS_PASS,
        'open_status' => NewProductWikiModel::OPEN_STATUS_UNCREATED,
        'is_delete' => NewProductWikiModel::NO_DELETED,
        'end_time[<=]' => date('Y-m-d 23:59:59', strtotime('-1 day')),
        'end_time[>=]' => date('Y-m-d 00:00:00', strtotime('-1 day')),
    ];
    $lists = NewProductWikiModel::select("*", $where);
    foreach ($lists as $list) {
        try {
            $start_time = date('Y-m-d H:i:s');
            $end_time = date('Y-m-d H:i:s', strtotime("+5 minutes"));
            //开奖时间
            $at_time = date('Y-m-d H:i:s', strtotime("+5 minutes"));

            if ((int)$list['type'] === NewProductWikiModel::SUPER_PDT) {
                $prize_num = $list['prize_num'];
                $lottery_type = \Doraemon\service\Lottery\Lottery::LOTTERY_BRAND_WIKI_TYPE;
                $prize_name = $list['name'];
            } else {
                $prize_num = 3;
                $lottery_type = \Doraemon\service\Lottery\Lottery::LOTTERY_BRAND_JD_TYPE;
                $prize_name = '京东卡';
            }
            $res = \Doraemon\service\Lottery\Lottery::createBrandLottery($prize_name, $prize_num, $start_time,
                $end_time, $at_time, $lottery_type);
            $log['info'] = $list;


            if (!$res) {
                continue;
            }
            $prize_id = $res['prize_id'];
            $series_id = $res['series_id'];
            $join_where = [
                'nid' => $list['id'],
                'GROUP' => 'uid'
            ];
            $join_uids = \Biz\model\NewProduct\NewProductJoinRecordModel::select('uid', $join_where);
            foreach ($join_uids as $key => $join_uid) {
                if (in_array($join_uid, $uids, false)) {
                    unset($join_uids[$key]);
                }
            }
            if (!$join_uids) {
                continue;
            }

            $add_brand_lottery_res = \Doraemon\service\Lottery\Lottery::addBrandLottery($prize_id, $series_id,
                $join_uids);


            $log['params'] = [
                'prize_name' => $prize_name,
                'prize_num' => $prize_num,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'at_time' => $at_time,
                'lottery_type' => $lottery_type
            ];
            $log['res'] = $res;
            $log['add_brand_lottery_res'] = $add_brand_lottery_res ?? [];
            \Doraemon\tools\Log::info('新品速递-抽奖记录', $log);

            $data['nid'] = $list['id'];
            $data['basic_id'] = $list['basic_id'];
            $data['series_id'] = $series_id;
            $data['activity_id'] = $res['activity_id'];
            $data['prize_id'] = $prize_id;
            $data['type'] = $list['type'];
            $lottery_log_id = NewProductLotteryLogModel::first(['nid' => $list['id']], 'id');
            if ($lottery_log_id) {
                NewProductWikiModel::update([
                    'open_status' => NewProductWikiModel::OPEN_STATUS_CREATED,
                    'update_time' => date('Y-m-d H:i:s')
                ], ['id' => $list['id']]);
                continue;
            }
            var_dump('入库数据' . json_encode($data));
             NewProductLotteryLogModel::action(function () use ($list, $data, &$result) {
                $result = NewProductLotteryLogModel::insert($data);
                if ($result->rowCount() == 0) {
                    $sql_log = NewProductLotteryLogModel::log();
                    \Doraemon\tools\Log::error('创建抽奖记录失败:', compact('list', 'sql_log'));
                    return false; // 回滚
                }
                //更新状态为已创建开奖任务
                $result = NewProductWikiModel::update([
                    'open_status' => NewProductWikiModel::OPEN_STATUS_CREATED,
                    'update_time' => date('Y-m-d H:i:s')
                ], ['id' => $list['id']]);
                if ($result->rowCount() == 0) {
                    $sql_log = NewProductWikiModel::log();
                    \Doraemon\tools\Log::error('更新抽奖状态失败:', compact('list', 'sql_log'));
                }
            });
            var_dump('事务返回值' . $result);
            if (!$result->rowCount()) {
                \Doraemon\tools\Log::info('新建抽奖-回滚', $list);
            }
        } catch (\Exception $e) {
            \Doraemon\tools\Log::error('创建新品速递抽奖_error:' . $e->getMessage(), $lists);
        }
    }
    $page++;
} while ($lists);

$end = microtime(true);
$time = $end - $start;
$second = round($time, 3);
var_dump('完成时间：' . date('Y-m-d H:i:s') . '   总耗时:' . $second . '秒');

